package cc.monggo.third.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ThirdAuthClient extends BaseClient {
	
	private static Log logger = LogFactory.getLog(ThirdAuthClient.class);

	public static String getAccessToken(HashMap<String,String> params){		
		StringBuffer sb = new StringBuffer();
		sb.append(params.get("path")).
		append("?").append("client_id=").append(params.get("client_id")).
		append("&").append("client_secret=").append(params.get("client_secret")).
		append("&").append("grant_type=").append(params.get("grant_type")).
		append("&").append("redirect_uri=").append(params.get("redirect_uri")).
		append("&").append("code=").append(params.get("code"));
		
		params.put("path", sb.toString());
		return post(params);	
	}
	
	public static String getUser(HashMap<String,String> params){	
		StringBuffer sb = new StringBuffer();
		sb.append(params.get("path")).append("?").append("uid=").append(params.get("uid"));
		
		//sb.append(params.get("path"));
		
		params.put("path", sb.toString());
		return getSSL(params);
	}
	
	public static String get(HashMap<String,String> params){
		String host 	= params.get("host") + "";
		int port 		= Integer.valueOf(params.get("port") + "");
		String protocol = params.get("protocol") + "";
		String path 	= params.get("path") + "";
		
		HttpClient client = new HttpClient();
		HttpMethod getMethod = new GetMethod(path);
		
		client.getHostConfiguration().setHost(host, port, protocol);
		
		try{
			client.executeMethod(getMethod);
			if(getMethod.getStatusCode() == 200){
				logger.info("请求成功: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
				byte body[] = getMethod.getResponseBody();
				return new String(body,0,body.length);
			}else{
				logger.warn("请求失败: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
			}
		}catch(Exception e){e.printStackTrace();}	
		
		return null;
	}
	
	public static String getSSL(HashMap<String,String> params){
		GetMethod method = null;
		method = new GetMethod(params.get("path"));
		
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		init(params);	
		
		try{		
			InetAddress ipaddr = InetAddress.getLocalHost();
			List<Header> headers = new ArrayList<Header>();		
			headers.add(new Header("Authorization", "OAuth2 " + params.get("access_token")));
			headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
			client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);

			client.executeMethod(method);
			
			if(method.getStatusCode() == 200){		
				logger.info("请求成功: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
				BufferedReader buffer = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
				StringBuffer body = new StringBuffer();
				for(String tempstr = ""; (tempstr = buffer.readLine()) != null;){
					body = body.append(tempstr);
				}
				return body.toString();
			}else{
				logger.warn("请求失败: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
			}
		}catch(Exception e){
			e.printStackTrace();
		}	
		
		finally{
			method.releaseConnection();
		}
		
		return null;
	}
	
	public static String post(HashMap<String,String> params){
		PostMethod method = null;
		method = new PostMethod(params.get("path"));
		init(params);
		try{
			client.executeMethod(method);
			if(method.getStatusCode() == 200){
				logger.info("请求成功: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
				byte body[] = method.getResponseBody();
				return new String(body,0,body.length);
			}else{
				logger.warn("请求失败: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
			}
		}catch(Exception e){e.printStackTrace();}
		
		finally{
			method.releaseConnection();
		}
		return null;
	}
	
	public static String postSSL(HashMap<String,String> params){
		PostMethod method = null;
		method = new PostMethod(params.get("path"));
		
		NameValuePair[] data = {
		          new NameValuePair("client_id", params.get("client_id")),
		          new NameValuePair("client_secret", params.get("client_secret")),
		          new NameValuePair("grant_type", params.get("grant_type")),
		          new NameValuePair("redirect_uri", params.get("redirect_uri")),
		          new NameValuePair("code", params.get("code"))
		        };
		method.setRequestBody(data);		
		//ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		//Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		init(params);
		try{
			client.executeMethod(method);
			if(method.getStatusCode() == 200){
				logger.info("请求成功: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
				BufferedReader buffer = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
				StringBuffer body = new StringBuffer();
				for(String tempstr = ""; (tempstr = buffer.readLine()) != null;){
					body = body.append(tempstr);
				}
				return body.toString();	
			}else{
				logger.warn("请求失败: " + params.get("protocol") + "://" + params.get("host") + ":" + Integer.valueOf(params.get("port")));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		finally{
			method.releaseConnection();
		}
		return null;
	}

}
